package com.len.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.len.base.BaseController;
import com.len.core.annotation.Log;
import com.len.entity.*;
import com.len.exception.MyException;
import com.len.service.*;
import com.len.util.BeanUtil;
import com.len.util.JsonUtil;
import com.len.util.ReType;
import com.len.util.UploadUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("quotation")
public class QuotationController extends BaseController {

    @Autowired
    private ProductService productService;
    @Autowired
    private TaskDetailsService taskDetailsService;
    @Autowired
    private QuotationService quotationService;
    @Autowired
    private QuotationSampleService quotationSampleService;
    @Autowired
    private QuotationDesignService quotationDesignService;
    @Autowired
    private QuotationHandleService quotationHandleService;
    @Autowired
    private ProductDemandService productDemandService;
    @Autowired
    UploadUtil uploadUtil;
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //跳转界面
    @GetMapping(value = "showAddQuotation")
    public String goAddQuotation(Model model) {
        return "/act/quotation/add-quotation";
    }

    //初始化界面，刚点击时的方法
    @GetMapping(value = "/showQuotation")
    @RequiresPermissions("quotation:show")
    public String showQuotation(Model model) {
        return "/act/quotation/quotationList";
    }

    //请求数据，查询所有数据
    @RequestMapping("/showQuotationList")
    @ResponseBody
    @RequiresPermissions("quotation:show")
    public ReType showQuotation(Model model, TQuotation quotation, String page, String limit) {
        ReType reType = quotationService.show(quotation, Integer.valueOf(page), Integer.valueOf(limit));
        return reType;
    }

    @Log(desc = "添加报价单", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation(value = "/addQuotation", httpMethod = "POST", notes = "添加报价单")
    @PostMapping("/addQuotation")
    @ResponseBody
    public JsonUtil addMenu(TQuotation quotation, Model model) {
        JsonUtil jsonUtil = new JsonUtil();
        jsonUtil.setFlag(false);
        if (quotation == null) {
            jsonUtil.setMsg("获取数据失败");
            return jsonUtil;
        }
//        if (tProductNotice.getOrderNo() ) {y
//            jsonUtil.setMsg("参数为空");
//        }
        try {
            quotation.setState("否");
            quotationService.insertSelective(quotation);
            List<TQuotationDesign> quotationDesigns = quotation.getQuotationDesigns();
            List<TQuotationSample> quotationSamples = quotation.getQuotationSamples();
            List<TQuotationHandle> quotationHandles = quotation.getQuotationHandles();
            if(null!=quotationDesigns) {
                for (TQuotationDesign quotationDesign : quotationDesigns
                ) {
                    quotationDesign.setOrderNo(quotation.getOrderNo());
                    quotationDesignService.insertSelective(quotationDesign);
                }
            }
            if(null!=quotationSamples) {
                for (TQuotationSample quotationSample : quotationSamples
                ) {
                    quotationSample.setOrderNo(quotation.getOrderNo());
                    quotationSampleService.insertSelective(quotationSample);
                }
            }
            if(null!=quotationHandles) {
                for (TQuotationHandle quotationHandle : quotationHandles
                ) {
                    quotationHandle.setOrderNo(quotation.getOrderNo());
                    quotationHandleService.insertSelective(quotationHandle);
                }
            }
                jsonUtil.setMsg("添加成功");
        } catch (MyException e) {
            e.printStackTrace();
            jsonUtil.setMsg("添加失败");
        }
        return jsonUtil;
    }

    @Log(desc = "删除报价单", type = Log.LOG_TYPE.DEL)
    @PostMapping("/delQuotation")
    @ResponseBody
    public JsonUtil del(String id) {
        try {
            TQuotation tProductNotice = quotationService.selectByPrimaryKey(id);
            quotationDesignService.delAllByOrderNo(tProductNotice.getOrderNo());
            return quotationService.del(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JsonUtil jsonUtil = new JsonUtil();
        jsonUtil.setMsg("删除失败");
        return jsonUtil;
    }

    @GetMapping(value = "detailquotation")
    public String detailquotation(String id, Model model, boolean detail) {
        if (StringUtils.isNotEmpty(id)) {
            TQuotation quotation = quotationService.selectByPrimaryKey(id);
            List<TQuotationSample> quotationSamples = quotationSampleService.selectAllByOrderNo(quotation.getOrderNo());

            List<TQuotationDesign> quotationDesigns = quotationDesignService.selectAllByOrderNo(quotation.getOrderNo());
            List<TQuotationHandle> quotationHandles = quotationHandleService.selectAllByOrderNo(quotation.getOrderNo());

            List<TProductDemand> productDemands = productDemandService.selectAllByOrderNo(quotation.getOrderNo());
            model.addAttribute("quotation", quotation);
            model.addAttribute("quotationSamples", quotationSamples);
            model.addAttribute("quotationDesigns", quotationDesigns);
            model.addAttribute("quotationHandles", quotationHandles);
            model.addAttribute("productDemands", productDemands);
        }
        model.addAttribute("detail", detail);
        return "/act/quotation/update-quotation";
    }

    @Log(desc = "更新生产通知单", type = Log.LOG_TYPE.ADD)
    @PostMapping("/updateQuotation")
    @ResponseBody
    public JsonUtil updateProduct(@RequestBody JSONObject tProductNotice) {

        List<TProductDemand> productDemands = JSON.parseArray(tProductNotice.getString("taskDetails"),TProductDemand.class);
        tProductNotice.remove("taskDetails");
        TQuotation quotation = JSONObject.toJavaObject(tProductNotice,TQuotation.class);
        TQuotation oldproduct = quotationService.selectByPrimaryKey(quotation.getId());


        BeanUtil.copyNotNullBean(quotation, oldproduct);
        quotationService.updateByPrimaryKeySelective(oldproduct);

        for(int i =0;i< productDemands.size();i++){
            TProductDemand oldTaskDetail = productDemandService.selectByPrimaryKey(productDemands.get(i).getId());
            if(null!=oldTaskDetail) {
                BeanUtil.copyNotNullBean(productDemands.get(i), oldTaskDetail);
                productDemandService.updateByPrimaryKeySelective(oldTaskDetail);
            }else {
                productDemandService.insert(productDemands.get(i));
            }
        }

        return JsonUtil.sucess("保存成功");
    }

    @RequestMapping("/showProductQuotation")
    @ResponseBody
    public ReType showDemand(String id, Model model, boolean detail) {
        ReType reType = new ReType();
        //根据orderNo查询所有的子表
        List<TProductDemand> taskDetails = productDemandService.selectAllByOrderNo(id);
        reType.setData(taskDetails);
        return reType;
    }

    @PostMapping("/download")
    public void UserExcelDownloads(HttpServletResponse response, String id) throws IOException {
        TQuotation quotation = quotationService.selectByPrimaryKey(id);
        List<TQuotationSample> quotationSamples = quotationSampleService.selectAllByOrderNo(quotation.getOrderNo());
        List<TProductDemand>  productDemands = productDemandService.selectListByOrderNo(quotation.getOrderNo());

        List<TQuotationDesign> quotationDesigns = quotationDesignService.selectAllByOrderNo(quotation.getOrderNo());
        List<TQuotationHandle> quotationHandles = quotationHandleService.selectAllByOrderNo(quotation.getOrderNo());


        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("报价单");
        sheet.setColumnWidth(0, 20 * 256);//设置列的宽度
        sheet.setColumnWidth(1, 20 * 256);//设置列的宽度
        sheet.setColumnWidth(2, 20 * 256);//设置列的宽度
        sheet.setColumnWidth(3, 20 * 256);//设置列的宽度
        sheet.setColumnWidth(4, 20 * 256);//设置列的宽度
        sheet.setColumnWidth(5, 20 * 256);//设置列的宽度
        String fileName = "体检信息" + ".xls";
        CellStyle style = workbook.createCellStyle();
        //水平垂直居中
        style.setAlignment(HorizontalAlignment.CENTER);//水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中

        CellStyle styleLeft = workbook.createCellStyle();
        //水平垂直居中
        styleLeft.setAlignment(HorizontalAlignment.LEFT);//水平居中
        styleLeft.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        styleLeft.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        styleLeft.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //第一行
        Row row0 = sheet.createRow(0);
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));
        row0.createCell(0).setCellValue("山东创联三维科技有限公司");
        row0.getCell(0).setCellStyle(style);
        sheet.getRow(0).setHeight((short) 1000);
        //第二行
        Row row1 = sheet.createRow(1);
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 4));
        row1.createCell(0).setCellValue("日期");
        row1.createCell(5).setCellValue(sdf.format(quotation.getAddTime()));
        //第三行
        Row row2 = sheet.createRow(2);
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 1, 5));
        row2.createCell(0).setCellValue("联系人："+quotation.getSaleName());
        row2.createCell(1).setCellValue("xxx"+quotation.getSaleName());
        row2.createCell(2).setCellValue("ccc"+quotation.getSaleName());
        row2.createCell(5).setCellValue("wwwwwwwwwwwwwwwww"+quotation.getSaleName());
        //第四行
        Row row3 = sheet.createRow(3);
        sheet.addMergedRegion(new CellRangeAddress(3, 3, 1, 2));
        sheet.addMergedRegion(new CellRangeAddress(3, 3, 4, 5));
        row3.createCell(0).setCellValue("Mobile：");
        row3.createCell(1).setCellValue(quotation.getSalePhone());
        row3.createCell(3).setCellValue("Email:");
        row3.createCell(4).setCellValue("");
        //第五行
        Row row4 = sheet.createRow(4);
        sheet.addMergedRegion(new CellRangeAddress(4, 4, 1, 5));
        row4.createCell(0).setCellValue("Add：");
        row2.createCell(1).setCellValue("");
        //第六行
        Row row5 = sheet.createRow(5);
        sheet.addMergedRegion(new CellRangeAddress(5, 5, 0, 5));
        row5.createCell(0).setCellValue("3D打印报价单");
        row5.getCell(0).setCellStyle(style);
        sheet.getRow(5).setHeight((short) 1000);
        //第七行
        Row row6 = sheet.createRow(6);
        sheet.addMergedRegion(new CellRangeAddress(6, 6, 1, 5));
        row6.createCell(0).setCellValue("公司名称：");
        row6.createCell(1).setCellValue(quotation.getCompany());
        //第八行
        Row row7 = sheet.createRow(7);
        sheet.addMergedRegion(new CellRangeAddress(7, 7, 1, 5));
        row7.createCell(0).setCellValue("收件地址：");
        row7.createCell(1).setCellValue(quotation.getConpanyAdress());
        //第九行
        Row row8 = sheet.createRow(8);
        sheet.addMergedRegion(new CellRangeAddress(8, 8, 3, 5));
        row8.createCell(0).setCellValue("联 系 人：");
        row8.createCell(1).setCellValue(quotation.getCompanyContact());
        row8.createCell(2).setCellValue("联系电话：");
        row8.createCell(3).setCellValue(quotation.getCompanyPhone());
        //第十行
        Row row9 = sheet.createRow(9);
        sheet.addMergedRegion(new CellRangeAddress(9, 9, 1, 5));
        row9.createCell(0).setCellValue("联系邮箱：");
        row9.createCell(1).setCellValue("");
        //第11行
        Row row10 = sheet.createRow(10);
        sheet.addMergedRegion(new CellRangeAddress(10, 10, 0, 5));
        row10.createCell(0).setCellValue("设计");
        row10.getCell(0).setCellStyle(styleLeft);
        row10.setHeight((short) 1000);
        //第12行
        Row row11 = sheet.createRow(11);
        row11.createCell(0).setCellValue("序号");
        row11.createCell(1).setCellValue("样件名称");
        row11.createCell(2).setCellValue("设计类型");
        row11.createCell(3).setCellValue("数量/件");
        row11.createCell(4).setCellValue("小计");
        row11.createCell(5).setCellValue("合计/元");
        //第13行到15行
        for (int i = 0; i < productDemands.size(); i++) {
            Row rowi = sheet.createRow(i + 12);
            rowi.createCell(0).setCellValue(i + 1);
            TProductDemand productDemand = productDemands.get(i);
            rowi.createCell(1).setCellValue(productDemand.getSample());
            rowi.createCell(2).setCellValue(productDemand.getDesign());
            rowi.createCell(3).setCellValue(productDemand.getNumber());
            rowi.createCell(4).setCellValue(productDemand.getSubtotal());
            rowi.createCell(5).setCellValue(quotation.getDesignMoney());
        }
        sheet.shiftRows(15, 15, -1);
        //第17行
        Row row16 = sheet.createRow(16);
        sheet.addMergedRegion(new CellRangeAddress(16, 16, 0, 5));
        row16.createCell(0).setCellValue("打印");
        row16.getCell(0).setCellStyle(styleLeft);
        sheet.getRow(16).setHeight((short) 1000);

        //第18行
        Row row17 = sheet.createRow(17);
        row17.createCell(0).setCellValue("序号");
        row17.createCell(1).setCellValue("样件名称");
        row17.createCell(2).setCellValue("材料类型");
        row17.createCell(3).setCellValue("数量/件");
        row17.createCell(4).setCellValue("小计");
        row17.createCell(5).setCellValue("合计/元");
        //第19行到21行
        for (int i = 0; i < productDemands.size(); i++) {

            Row rowi = sheet.createRow(i + 18);
            rowi.createCell(0).setCellValue(i + 1);
            TProductDemand productDemand = productDemands.get(i);
            rowi.createCell(1).setCellValue(productDemand.getSample());
            rowi.createCell(2).setCellValue(productDemand.getMaterial());
            rowi.createCell(3).setCellValue(productDemand.getNumber());
            rowi.createCell(4).setCellValue(productDemand.getSubtotal());
            rowi.createCell(5).setCellValue(quotation.getSampleMoney());
        }
        //第22行
        Row row21 = sheet.createRow(21);
        sheet.addMergedRegion(new CellRangeAddress(21, 21, 0, 5));
        row21.createCell(0).setCellValue("后处理");
        row21.getCell(0).setCellStyle(styleLeft);
        sheet.getRow(21).setHeight((short) 1000);
        //第23行
        Row row22 = sheet.createRow(22);
        row22.createCell(0).setCellValue("序号");
        row22.createCell(1).setCellValue("样件名称");
        row22.createCell(2).setCellValue("工艺类型");
        row22.createCell(3).setCellValue("数量/件");
        row22.createCell(4).setCellValue("小计");
        row22.createCell(5).setCellValue("合计/元");
        //第24行到26行
        for (int i = 0; i < productDemands.size(); i++) {
            Row rowi = sheet.createRow(i + 23);
            rowi.createCell(0).setCellValue(i + 1);
            TProductDemand productDemand = productDemands.get(i);
            rowi.createCell(1).setCellValue(productDemand.getSample());
            rowi.createCell(2).setCellValue(productDemand.getTechnology());
            rowi.createCell(3).setCellValue(productDemand.getNumber());
            rowi.createCell(4).setCellValue(productDemand.getSubtotal());
            rowi.createCell(5).setCellValue(quotation.getHandleMoney());

        }
        //第27行
        Row row26 = sheet.createRow(26);
        sheet.addMergedRegion(new CellRangeAddress(26, 26, 0, 5));
        row26.createCell(0).setCellValue("交期：" + sdf.format(quotation.getDeliveryDate()));
        //第28行
        Row row27 = sheet.createRow(27);
        sheet.addMergedRegion(new CellRangeAddress(27, 27, 0, 1));
        sheet.addMergedRegion(new CellRangeAddress(27, 27, 2, 5));
        row27.createCell(0).setCellValue("合计/元：");
        row27.createCell(2).setCellValue(quotation.getAmount());
        //第29行
        Row row28 = sheet.createRow(28);
        sheet.addMergedRegion(new CellRangeAddress(28, 28, 0, 1));
        sheet.addMergedRegion(new CellRangeAddress(28, 28, 2, 5));
        row28.createCell(0).setCellValue("税点：");
        row28.createCell(2).setCellValue(quotation.getTax());
        //第30行
        Row row29 = sheet.createRow(29);
        sheet.addMergedRegion(new CellRangeAddress(29, 29, 0, 1));
        sheet.addMergedRegion(new CellRangeAddress(29, 29, 2, 5));
        row29.createCell(0).setCellValue("运费：");
        row29.createCell(2).setCellValue(quotation.getPostage());
        //第31行
        Row row30 = sheet.createRow(30);
        sheet.addMergedRegion(new CellRangeAddress(30, 30, 0, 1));
        sheet.addMergedRegion(new CellRangeAddress(30, 30, 2, 5));
        row30.createCell(0).setCellValue("总合计/元（大写人民币）：");
        row30.createCell(2).setCellValue(quotation.getTotalMoney());
        //第32行
        Row row31 = sheet.createRow(31);
        //第33行
        Row row32 = sheet.createRow(32);
        sheet.addMergedRegion(new CellRangeAddress(32, 32, 0, 5));
        row32.createCell(0).setCellValue("付款信息");

        //第34行
        Row row33 = sheet.createRow(33);
        sheet.addMergedRegion(new CellRangeAddress(33, 33, 0, 5));
        row33.createCell(0).setCellValue("名    称：山东创联三维科技有限公司");

        //第35行
        Row row34 = sheet.createRow(34);
        sheet.addMergedRegion(new CellRangeAddress(34, 34, 0, 5));
        row34.createCell(0).setCellValue("开户银行：中信银行股份有限公司济宁分行");

        //第36行
        Row row35 = sheet.createRow(35);
        sheet.addMergedRegion(new CellRangeAddress(35, 35, 0, 5));
        row35.createCell(0).setCellValue("  银行账户：8112501011900778195");

        //第37行
        Row row36 = sheet.createRow(36);
        sheet.addMergedRegion(new CellRangeAddress(36, 41, 0, 5));
        row36.createCell(0).setCellValue("    备注：\n" +
                "1、此金额含：增值税发票。\n" +
                "2、运费说明：以上价格含运费，超出最低起运标准，按快递公司收费标准另行收取。\n" +
                "3、付款说明：（1）单结，方式按照合同规定执行； \n" +
                "            （2）只接受支票、电汇、转账、微信、支付宝，不收期票和银行承兑汇票。          \n" +
                "4、报价有效期限：此报价单有效期为报价日期起15天内。");

        //第43行
        Row row42 = sheet.createRow(42);
        //第44行
        Row row43 = sheet.createRow(43);
        sheet.addMergedRegion(new CellRangeAddress(43, 43, 2, 5));
        row43.createCell(0).setCellValue("公司名称：");
        row43.createCell(1).setCellValue("（公章）");
        row43.createCell(2).setCellValue("山东创联三维科技有限公司");
        //第45行
        Row row44 = sheet.createRow(44);
        //第46行
        Row row45 = sheet.createRow(45);
        row43.createCell(0).setCellValue("审核：");
        //第47行
        Row row46 = sheet.createRow(46);
        //第48行
        Row row47 = sheet.createRow(47);
        sheet.addMergedRegion(new CellRangeAddress(47, 47, 3, 5));
        row47.createCell(3).setCellValue("本报价单盖章后有效");
        response.setContentType("application/vnd.ms-excel;charset=utf-8");

        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }
    /**
     * 头像上传 目前首先相对路径
     */
    @PostMapping(value = "upload")
    @ResponseBody
    public JsonUtil imgUpload(HttpServletRequest req, @RequestParam("file") MultipartFile file,
                              ModelMap model) {
        String fileName = uploadUtil.upload(file);
        JsonUtil j = new JsonUtil();
        j.setMsg(fileName);
        return j;
    }
    @RequestMapping("/trans")
    @ResponseBody
    public JsonUtil trans(String id) {
        JsonUtil jsonUtil = new JsonUtil();
        try {
            TQuotation quotation = quotationService.selectByPrimaryKey(id);
            List<TProductNotice>  tProductNotice = productService.selectListByOrderNo(quotation.getOrderNo());
            if(tProductNotice.size() != 0){
                jsonUtil.setMsg("已有相应合同编号的通知单");
                return jsonUtil;
            }
//            List<TProductDemand>  productDemands = productDemandService.selectListByOrderNo(quotation.getOrderNo());

            TProductNotice productNotice = new TProductNotice();
            productNotice.setOrderNo(quotation.getOrderNo());
            productNotice.setSaleName(quotation.getSaleName());
            productNotice.setCustomerAddress(quotation.getConpanyAdress());
            productNotice.setDeliveryDate(quotation.getDeliveryDate());
            productNotice.setNoticeTime(new Date());
            productNotice.setIspay("否");
            productNotice.setPhoto(quotation.getFile());
//            String orderNo = quotation.getOrderNo();
//            List<TTaskDetails> taskDetails = new ArrayList<>();
//            for(int i =0;i<productDemands.size();i++){
//                TProductDemand productDemand = productDemands.get(i);
//                TTaskDetails taskDetail = new TTaskDetails();
//                taskDetail.setOrderNo(orderNo);
//                taskDetail.setSampleName(productDemand.getSample());
//                taskDetail.setQuantity(Long.parseLong(productDemand.getNumber()));
//                taskDetail.setMaterial(productDemand.getMaterial());
//                taskDetail.setRequirement(productDemand.getTechnology());
//                taskDetailsService.insert(taskDetail);
//                taskDetails.add(taskDetail);
//            }
//            productNotice.setTaskDetails(taskDetails);
            productService.insert(productNotice);
        }catch (Exception e){
            e.printStackTrace();
            jsonUtil.setMsg("转换失败");
            return jsonUtil;
        }
        jsonUtil.setMsg("ok");
        return jsonUtil;
    }

    @RequestMapping("/check")
    @ResponseBody
    public JsonUtil check(String id) {
        JsonUtil jsonUtil = new JsonUtil();
        try {
            TQuotation quotation = quotationService.selectByPrimaryKey(id);
            quotation.setState("审核通过");
            quotationService.updateByPrimaryKey(quotation);
        }catch (Exception e){
            e.printStackTrace();
            jsonUtil.setMsg("转换失败");
            return jsonUtil;
        }
        jsonUtil.setMsg("ok");
        return jsonUtil;
    }

    private String compareDesigon(String nane,List<TQuotationHandle> quotationHandles){
        for(TQuotationHandle quotationHandle : quotationHandles){
            if(quotationHandle.getSample().equals(nane)){
                return quotationHandle.getTechnology();
            }

        }
        return null;
    }
}
